﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using S4Store.Models.Report;
using S4Store.Domain;
using S4Store.Service;
using S4Store.Domain.AfterSaleKpi;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using S4Store.Models;
using S4Store.Models.AfterSaleReport;

namespace S4Store.Controllers
{
    public class AfterSaleHealthyReportController : ReportBaseController
    {
        public AfterSaleCarKPIService AfterSaleCarKPIService { get; set; }
        public EmployeeService EmployeeService { get; set; }
        public DeadStockService DeadStockService { get; set; }
        public ActionResult Index()
        {
            AfterSaleHealthyIndexModel model = new AfterSaleHealthyIndexModel();
            using (var t = new Transtion())
            {
                t.Inject(AfterSaleCarKPIService);
                t.Inject(EmployeeService);
                //时间进度
                decimal 时间进度 = (decimal)Month.LastOrNowDay() / (decimal)(Month.LastDay());

                //维修总产值进度差异;
                decimal 维修总产值目标 = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o=>o.IsConfirmed).Sum(o=>o.BYWXCZMB_MonthMaintenanceTargetValue);
                decimal 维修总产值累计完成额 = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.QTWXCZ_MaintainOtherValue+o.WQBYCZ_Maintain5KValue+o.SQBYCZ_Maintain10KValue);
                model.常态维修动态 = ((维修总产值目标 == 0 ? 0 : 维修总产值累计完成额 / 维修总产值目标) - 时间进度)*100;


                //事故维修动态
                decimal 事故车产值目标 = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.BYSGCCZBM_MonthAacidentCarTargetValue);
                decimal 事故车产值完成额 = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.SGCCZ_AccidentCarValue);
                model.事故维修动态 = ((事故车产值目标 == 0 ? 0 : 事故车产值完成额 / 事故车产值目标) - 时间进度)*100;

                //客户管理动态
                int[] SAemploys = EmployeeService.GetEnableEmployee(Store.Id, EmployeeType.ServiceConsultant).Select(o => o.Id).ToArray();
                S4Store.Models.AfterSaleReport.AfterSaleReportServiceAdvisorModel model1 = new AfterSaleReportServiceAdvisorModel();
                model1.StandardConfig = AfterSaleCarKPIService.GetAfterSaleMonthStandardConfig(Month.Year, Month.Month, Store.Id);
                model1.SADayDatas = AfterSaleCarKPIService.GetAfterSaleServiceAdvisorDayInputs(Month.Year, Month.Month, SAemploys);
                model1.MonthTargets = AfterSaleCarKPIService.GetAfterSaleServiceAdvisorMonthTargets(Month.Year, Month.Month, SAemploys);
                model1.MonthTarget = AfterSaleCarKPIService.GetAfterSaleServiceAdvisorMonthTargets(Month.Year, Month.Month, SAemploys);
                decimal 目标客户流失率 = 0;
                if (model1.StandardConfig != null) 目标客户流失率 = model1.StandardConfig.事实流失率目标;
                model.客户管理动态 = 目标客户流失率- model1.GetAvgSSKHLSL(Month.Year, Month.Month);

                //用品销售动态
                //用品销售完成进度和时间进度的差异
                AfterSaleProductModel model2 = new AfterSaleProductModel();
                model2.DMMonthTargets = AfterSaleCarKPIService.GetAfterSaleCarDecoratingMonthConfigs(Month.Year, Month.Month, Store.Id);
                model2.DMDayDatas = AfterSaleCarKPIService.GetAfterSaleCarDecoratingDayInputs(Month.Year, Month.Month, Store.Id);
                decimal 用品销售完成率 = model2.z_ZHXSJD(Month.Year,Month.Month);
                model.用品销售动态 = (用品销售完成率/100 - 时间进度) * 100;

                //养护产品完成进度和时间进度的差异
                decimal 养护产品销售完成率 = model2.z_YHCPXSJD(Month.Year, Month.Month);
                model.养护产品动态 = (养护产品销售完成率/100 - 时间进度) * 100;

                //var 实际备件库存 = DeadStockService.GetQuery<Domain.AfterSaleKpi.SparePartsMonthInput>()
                //    .Where(o => o.StoreId == Store.Id)
                //    .Sum(o=>o.);



            }
            this.InjectReportModel(model);
            model.BarModel.Action = "Index";
            model.BarModel.Controller = "AfterSaleHealthyReport";
            model.BarModel.AddView(ReportBarModel.ViewItem.Month);
            return View(model);
        }

        public ActionResult CarTypeQuery()
        {
            AfterSaleHealthyCarTypeModel model = new AfterSaleHealthyCarTypeModel();
            using (var t = new Transtion())
            {

                decimal 时间进度 = (decimal)Month.LastOrNowDay() / (decimal)(Month.LastDay());
                
                t.Inject(AfterSaleCarKPIService);
                model.应时台次 = (int)((decimal)AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.BYWXRCTCMB_MonthMaintainCarToFactoryTarget) * 时间进度);

                model.实际台次 = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.WXRCTC_MaintainCarToFactory);

                model.实际产值 = Math.Round(AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.WQBYCZ_Maintain5KValue + o.SQBYCZ_Maintain10KValue + o.QTWXCZ_MaintainOtherValue),2,MidpointRounding.AwayFromZero);

                model.应时产值 = Math.Round(AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed).Sum(o => o.BYWXCZMB_MonthMaintenanceTargetValue) * 时间进度,2,MidpointRounding.AwayFromZero); 

                ViewBag.时间进度 = 时间进度;

                this.InjectReportModel(model);
                model.BarModel.Action = "CarTypeQuery";
                model.BarModel.Controller = "AfterSaleHealthyReport";
                //model.BarModel.PlusItem = "<a target='navtab' class='historyrecord' title='销售台次历史记录' href='" + Url.Action("SaleHistroy") + "' ><span>历史数据查询</span></a>";
                model.BarModel.AddView(ReportBarModel.ViewItem.Month);
                t.Commit();

            }
            return View(model);
        }

        public ActionResult CarBrands_RCTC()
        {
            AfterSaleHealthyCarBrand_RCTCModel model = new AfterSaleHealthyCarBrand_RCTCModel();
            using (var t = new Transtion())
            {
                decimal 时间进度 = (decimal)Month.LastOrNowDay() / (decimal)(Month.LastDay());
                t.Inject(AfterSaleCarKPIService);

                model.RCTCList = new List<AfterSaleHealthyCarBrand_RCTCModel.RCTCMdel>();
                var queryMonth = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed);
                var queryDay = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed);

                var Brandlist = queryMonth.Select(o => o.CarBrand).Distinct();
                foreach (var item in Brandlist)
                {
                    model.RCTCList.Add(new AfterSaleHealthyCarBrand_RCTCModel.RCTCMdel()
                    {
                        车型ID = item.Id,

                        车型名称 = item.Name,

                        月应时台次 = queryMonth.Where(o => o.CarBrandId == item.Id).Sum(o => o.BYWXRCTCMB_MonthMaintainCarToFactoryTarget),

                        应时台次 = (int)Math.Round((decimal)(queryMonth.Where(o => o.CarBrandId == item.Id).Sum(o => o.BYWXRCTCMB_MonthMaintainCarToFactoryTarget)*时间进度),0,MidpointRounding.AwayFromZero),

                        实际台次 = queryDay.Where(o => o.CarBrandId == item.Id).Sum(o =>  o.WXRCTC_MaintainCarToFactory)
                    });
                }
                ViewBag.时间进度 = 时间进度;
                

                this.InjectReportModel(model);
                model.BarModel.Action = "CarBrands_RCTC";
                model.BarModel.Controller = "AfterSaleHealthyReport";
                model.BarModel.AddView(ReportBarModel.ViewItem.Month);
                t.Commit();
            }
            return View(model);
        }

        public ActionResult CarBrand_RCTCKPI(int brandid=0)
        {
            if (brandid == 0)
            {
                brandid = SearchCarBrandId ?? 0;
            }

            AfterSaleHealthyCarBrand_RCTCModel model = new AfterSaleHealthyCarBrand_RCTCModel();
            using (var t = new Transtion())
            {
                decimal 时间进度 = (decimal)Month.LastOrNowDay() / (decimal)(Month.LastDay());
                t.Inject(AfterSaleCarKPIService);

                model.MonthData = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed && o.CarBrandId == brandid).FirstOrDefault();

                model.DayDatas= AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed && o.CarBrandId == brandid).ToList();

                ViewBag.时间进度 = 时间进度;

                model.TimeRate = new Models.Chart.Pie();
                model.TimeRate.Width = 450;
                model.TimeRate.Height = 300;
                model.TimeRate.IsRate = true;
                model.TimeRate.YAxis = "%";
                model.TimeRate.Name = "时间进度";
                model.TimeRate.Data.Add("时间进度", 时间进度);
                model.TimeRate.Data.Add("剩余", 1 - 时间进度);

                this.InjectReportModel(model);
                model.BarModel.Action = "CarBrand_RCTCKPI";
                model.BarModel.Controller = "AfterSaleHealthyReport";
				if (
                           CurrentUser.Position == S4Store.Domain.Position.SystemManager ||
                           CurrentUser.Position == S4Store.Domain.Position.DealerTutors
                           )
		{
                model.BarModel.PlusItem = "<a class='historyrecord edit'  backtype='html' href='" + Url.Action("AddImproveGuide", "ImproveGuide", new { guidetype = S4Store.Domain.ImproveGuide.ImproveGuideType.AfterSale.ToInt() ,referdesc="售后管理>常态维修动态>车型查询>入厂台次完成进度差" }) + "' target='dialog' width='60%'><span >填写改善指导建议</span></a> <a class='historyrecord edit'  backtype='html' href='" + Url.Action("CarBrand_History", new { brandid = brandid }) + "' target='navtab'><span >历史查询</span></a>";
				}else
		{
			  model.BarModel.PlusItem = "<a class='historyrecord edit'  backtype='html' href='" + Url.Action("CarBrand_History", new { brandid = brandid }) + "' target='navtab'><span >历史查询</span></a>";
			}
                
                model.BarModel.AddView(ReportBarModel.ViewItem.Month);
                model.BarModel.SearchCarBrandId = brandid;
                t.Commit();
            }
            return View(model);
            
        }

        

        public ActionResult CarBrand_History(int brandid=0)
        {
            AfterSaleCarModelHistoryModel model = new AfterSaleCarModelHistoryModel();

            if (brandid == 0)
                brandid = SearchCarBrandId ?? 0;
            model.BrandId = brandid;

            DateTime start = DateTime.Now.AddMonths(-6);
            DateTime end = DateTime.Now;
            if (this.Start != null)
            {
                start = new DateTime(Start.Value.Year, Start.Value.Month, 1);
                end = new DateTime(End.Value.Year, End.Value.Month, End.Value.LastOrNowDay());
            }

            using (var t = new Transtion())
            {
                t.Inject(AfterSaleCarKPIService);

                model.CTDays = AfterSaleCarKPIService.GetAfterSaleCarKpiDayDataQuery().Where(o => o.IsConfirmed && o.AddTime <= end && o.AddTime >= start && o.CarBrandId == brandid && o.StoreId == Store.Id).ToList();

                model.CTMonths = AfterSaleCarKPIService.GetAfterSaleCarKpiMonthDataQuery().Where(o => o.IsConfirmed && o.Month <= end && o.Month >= start && o.CarBrandId == brandid && o.StoreId == Store.Id).ToList();

            }
            
            this.InjectReportModel(model);
            model.BarModel.Action = "CarBrand_History";
            model.BarModel.Controller = "AfterSaleHealthyReport";
            model.BarModel.AddView(ReportBarModel.ViewItem.StartEnd);
            model.BarModel.Start = start;
            model.BarModel.End = end;
            model.BarModel.SearchCarBrandId = brandid;

            return View(model);

        }

        #region 车型查询 - 维修产值
        public ActionResult CarBrands_WXCZ()
        {
            AfterSaleHealthyCarBrand_WXCZModel model = new AfterSaleHealthyCarBrand_WXCZModel();
            using (var t = new Transtion())
            {
                decimal 时间进度 = (decimal)Month.LastOrNowDay() / (decimal)(Month.LastDay());
                t.Inject(AfterSaleCarKPIService);

                model.RCTCList = new List<AfterSaleHealthyCarBrand_WXCZModel.WXCZMdel>();
                var queryMonth = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed);
                var queryDay = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed);
                var Brandlist = queryMonth.Select(o => o.CarBrand).Distinct();
                foreach (var item in Brandlist)
                {
                    model.RCTCList.Add(new AfterSaleHealthyCarBrand_WXCZModel.WXCZMdel()
                    {
                        车型ID = item.Id,

                        车型名称 = item.Name,

                        月应时产值  = queryMonth.Where(o => o.CarBrandId == item.Id).Sum(o => o.BYWXCZMB_MonthMaintenanceTargetValue),

                        应时产值 = Math.Round((decimal)(queryMonth.Where(o => o.CarBrandId == item.Id).Sum(o => o.BYWXCZMB_MonthMaintenanceTargetValue) * 时间进度), 2, MidpointRounding.AwayFromZero),

                        实际产值 = queryDay.Where(o => o.CarBrandId == item.Id).Sum(o => o.WQBYCZ_Maintain5KValue + o.SQBYCZ_Maintain10KValue + o.QTWXCZ_MaintainOtherValue)
                    });
                }
                ViewBag.时间进度 = 时间进度;

                this.InjectReportModel(model);
                model.BarModel.Action = "CarBrands_WXCZ";
                model.BarModel.Controller = "AfterSaleHealthyReport";
                model.BarModel.AddView(ReportBarModel.ViewItem.Month);
                t.Commit();
            }
            return View(model);
        }

        public ActionResult CarBrand_WXCZKPI(int brandid = 0)
        {
            if (brandid == 0)
                brandid = SearchCarBrandId ?? 0;

            AfterSaleHealthyCarBrand_RCTCModel model = new AfterSaleHealthyCarBrand_RCTCModel();
            using (var t = new Transtion())
            {
                decimal 时间进度 = (decimal)Month.LastOrNowDay() / (decimal)(Month.LastDay());
                t.Inject(AfterSaleCarKPIService);

                model.MonthData = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthConfigs(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed && o.CarBrandId == brandid).FirstOrDefault();

                model.DayDatas = AfterSaleCarKPIService.GetAfterSaleCarTypeMonthFinished(Month.Year, Month.Month, Store.Id).Where(o => o.IsConfirmed && o.CarBrandId == brandid).ToList();

                ViewBag.时间进度 = 时间进度;

                model.TimeRate = new Models.Chart.Pie();
                model.TimeRate.Width = 450;
                model.TimeRate.Height = 300;
                model.TimeRate.IsRate = true;
                model.TimeRate.YAxis = "%";
                model.TimeRate.Name = "时间进度";
                model.TimeRate.Data.Add("时间进度", 时间进度);
                model.TimeRate.Data.Add("剩余", 1 - 时间进度);

                this.InjectReportModel(model);
                model.BarModel.Action = "CarBrand_WXCZKPI";
                model.BarModel.Controller = "AfterSaleHealthyReport";
				if (
                           CurrentUser.Position == S4Store.Domain.Position.SystemManager ||
                           CurrentUser.Position == S4Store.Domain.Position.DealerTutors
                           )
		{
                model.BarModel.PlusItem = "<a class='historyrecord edit'  backtype='html' href='" + Url.Action("AddImproveGuide", "ImproveGuide", new { guidetype = S4Store.Domain.ImproveGuide.ImproveGuideType.AfterSale.ToInt() ,referdesc="售后管理>常态维修动态>车型查询>维修产值完成进度差" }) + "' target='dialog' width='60%'><span >填写改善指导建议</span></a> <a class='historyrecord edit'  backtype='html' href='" + Url.Action("CarBrand_WXCZHistory", new { brandid = brandid }) + "' target='navtab'><span >历史查询</span></a>";
				}else
		{
			  model.BarModel.PlusItem = "<a class='historyrecord edit'  backtype='html' href='" + Url.Action("CarBrand_WXCZHistory", new { brandid = brandid }) + "' target='navtab'><span >历史查询</span></a>";
			}

                model.BarModel.AddView(ReportBarModel.ViewItem.Month);
                model.BarModel.SearchCarBrandId = brandid;
                t.Commit();
            }
            return View(model);
        }

        public ActionResult CarBrand_WXCZHistory(int brandid=0)
        {
            AfterSaleCarModelHistoryModel model = new AfterSaleCarModelHistoryModel();

            if (brandid == 0)
                brandid = SearchCarBrandId ?? 0;
            model.BrandId = brandid;

            DateTime start = DateTime.Now.AddMonths(-6);
            DateTime end = DateTime.Now;
            if (this.Start != null)
            {
                start = new DateTime(Start.Value.Year, Start.Value.Month, 1);
                end = new DateTime(End.Value.Year, End.Value.Month, End.Value.LastOrNowDay());
            }

            using (var t = new Transtion())
            {
                t.Inject(AfterSaleCarKPIService);

                model.CTDays = AfterSaleCarKPIService.GetAfterSaleCarKpiDayDataQuery().Where(o => o.IsConfirmed && o.AddTime <= end && o.AddTime >= start && o.CarBrandId == brandid && o.StoreId == Store.Id).ToList();

                //model.CTMonths = AfterSaleCarKPIService.GetAfterSaleCarKpiMonthDataQuery().Where(o => o.IsConfirmed && o.Month <= end && o.Month >= start && o.CarBrandId == brandid && o.StoreId == Store.Id).ToList();

            }

            this.InjectReportModel(model);
            model.BarModel.Action = "CarBrand_WXCZHistory";
            model.BarModel.Controller = "AfterSaleHealthyReport";
            model.BarModel.AddView(ReportBarModel.ViewItem.StartEnd);
            model.BarModel.Start = start;
            model.BarModel.End = end;
            model.BarModel.SearchCarBrandId = brandid;

            return View(model);
        }

        #endregion
    }
}
